'''
 * @ author     ：廖传港
 * @ date       ：Created in 2020/10/29 11:09
 * @ description：该文件功能主要是将图片加载到内存
 * @ modified By：
 * @ ersion     : 
 * @File        : loading_pictures.py
'''

# -*- coding: utf-8 -*-

import os
import random
import sys
import numpy as np
import cv2

IMAGE_SIZE = 64


# 按照指定图像大小调整尺寸
def resize_image(image, height=IMAGE_SIZE, width=IMAGE_SIZE):
    top, bottom, left, right = (0, 0, 0, 0)

    # 获取图像尺寸
    h, w = image.shape

    # 对于长宽不相等的图片，找到最长的一边
    longest_edge = max(h, w)

    # 计算短边需要增加多上像素宽度使其与长边等长
    if h < longest_edge:
        dh = longest_edge - h
        top = dh // 2
        bottom = dh - top
    elif w < longest_edge:
        dw = longest_edge - w
        left = dw // 2
        right = dw - left
    else:
        pass

        # RGB颜色
    BLACK = [0, 0, 0]

    # 给图像增加边界，是图片长、宽等长，cv2.BORDER_CONSTANT指定边界颜色由value指定
    constant = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=BLACK)

    # 调整图像大小并返回
    return cv2.resize(constant, (height, width))


# 读取图片数据并与标签绑定
def read_path(images, labels, path_name, label):
    for dir_item in os.listdir(path_name):
        full_path = os.path.abspath(os.path.join(path_name, dir_item))
        image = cv2.imread(full_path,cv2.IMREAD_GRAYSCALE)
        image = resize_image(image, IMAGE_SIZE, IMAGE_SIZE)  ##把所有图片改成64*64大小的

        image = np.pad(image, ((1, 1), (1, 1)), 'constant')  # ,constant_values 缺省，则默认填充均为0
        # print("image.shape=", image.shape)
        images.append(image)
        labels.append(label)


def loaddata(parent_dir):
    images = []
    labels = []
    read_path(images, labels, parent_dir + "/cat", 1)
    read_path(images, labels, parent_dir + "/dog", 9)

    # 打乱顺序（图片和标签同步）
    state = np.random.get_state()
    np.random.shuffle(images)
    np.random.set_state(state)
    np.random.shuffle(labels)

    return images, labels


if __name__ == '__main__':
    images, labels = loaddata("D:/python/data/")

    print(labels)
